package com.horizon.manage.item.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.horizon.common.constrants.HorizonResultCodeEnum;
import com.horizon.common.util.HorizonUtil;
import com.horizon.manage.item.dto.ItemDTO;
import com.horizon.manage.item.converter.ItemEvdConverter;
import com.horizon.manage.item.entity.Item;
import com.horizon.manage.item.service.IItemService;
import com.horizon.manage.item.vo.ItemVO;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 项目controller.
 *
 * @author zhaoshb
 * @since 2022/12/7 22:41
 */
@RestController
@AllArgsConstructor
@RequestMapping("/horizon/item")
public class ItemController {

    private IItemService itemService;

    private ItemEvdConverter itemEvdConverter;

    @PostMapping("/create")
    @ApiOperation(value = "创建", notes = "创建")
    public R<Long> create(@RequestBody ItemDTO itemDTO) {
        Item item = itemEvdConverter.dtoToEntity(itemDTO);
        return itemService.save(item) ? R.data(item.getId()) : R.fail(ResultCode.FAILURE);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除", notes = "删除")
    public R<Object> delete(@RequestBody Long deviceId) {
        int rowAffected = itemService.getBaseMapper().deleteById(deviceId);
        return rowAffected == 1 ? R.data(null) : R.fail(HorizonUtil.getLocaleMessage(HorizonResultCodeEnum.DEVICE_NOT_EXIST));
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新", notes = "更新")
    public R<Object> update(@RequestBody ItemDTO dto) {
        Item item = itemEvdConverter.dtoToEntity(dto);
        return R.status(itemService.updateById(item));
    }

    @GetMapping("/list")
    @ApiOperation(value = "分页", notes = "传入cond以及排序条件")
    public R<IPage<ItemVO>> list(@ApiIgnore @RequestParam Map<String, Object> cond, Query query) {
        IPage<Item> pages = itemService.page(Condition.getPage(query), Condition.getQueryWrapper(cond, Item.class));
        return R.data(itemEvdConverter.pageVO(pages));
    }
}
